package com.shen.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shen.edu.entity.Subject;
import com.shen.edu.entity.excel.SubjectData;
import com.shen.edu.service.SubjectService;
import com.shen.servicebase.execptionhandler.GuliException;

/**
 * @program: guli_parent
 * @description: 监听器
 * @author: Mr.shen
 * @create: 2020-06-15 17:56
 **/
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public SubjectService subjectService;
    public SubjectExcelListener(SubjectService subjectService){
        this.subjectService = subjectService;
    }

    public SubjectExcelListener() {
    }

    /**
     * 因为SubjectExcelListener不能交给Spring管理，需要自己new，不能注入其它对象
     * 不能实现数据库操作
     * @param subjectData
     * @param analysisContext
     */
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new GuliException(20001,"文件为空");
        }
            //一行一行读取，有两个值，一个为一级分类一个为二级分类
            //判断一级分类是否重复
        Subject oneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if (oneSubject==null){
            //没有相同的就添加
            oneSubject = new Subject();
            oneSubject.setParentId("0");
            //一级分类名称
            oneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(oneSubject);
        }
        //二级分类
        //获取一级分类的id值
        String pid = oneSubject.getId();
        Subject twoSubject = this.existTwoSubject(subjectService, subjectData.getTowSubjectName(), pid);
        if(twoSubject == null){
            //没有相同的就添加
            twoSubject = new Subject();
            twoSubject.setParentId(pid);
            //二级分类名称
            twoSubject.setTitle(subjectData.getTowSubjectName());
            subjectService.save(twoSubject);
        }
    }

    /**
     * 判断一级分类不能重复添加
     */
    private Subject existOneSubject(SubjectService subjectService,String name){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        Subject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }
    /**
     * 判断二级分类不能重复添加
     */
    private Subject existTwoSubject(SubjectService subjectService,String name,String pid){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        Subject twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
